(function(win){
	var Z = win.Z;
	
	var bundle = new Z.Bundle({'tmpl' : 'user'});
	
	var loader, form;
	
	bundle.addEvent('a.clear', 'click', function(e){
		if(e.ctrlKey){
			Z.ajax({'url' : Z.route('user', 'clear')});
		}

		return false;
	});
	
	bundle.addEvent('thead a', 'click', function(){
		var field = $(this).data('field'),
		direction = (typeof $(this).data('direction') == 'undefined') ? 1 : $(this).data('direction');
		$(this).data('direction', direction * -1);
		loader.load({'orderField' : field, 'orderDirection' : direction});
		return false;
	});

	bundle.addEvent('tbody', 'click', 'a.edit', function(){
		var id = $(this).parent().siblings().first().find(':checkbox').val();
		Z.ajax({
			'url' : Z.route('user','find'),
			'data' : {'id' : id},
			'success' : function(data){
				form.open().fill(data);
			}
		});
		return false;
	});
	
	bundle.onload = function(){
		form = new Z.Form({
			'content' : bundle.find('script.form-tmpl').html(),
			'width' : 500,
			'action' : Z.route('user','set')
		});
		
		form.onopen = function(){
			Z.ajax({
				'url' : Z.route('group', 'simple'),
				'success' : function(data){
					Z.Form.fillSelect(form.find('select[name="group"]'), data);
				}
			});
		};

		form.onsubmit = function(){
			loader.reload();
		};
		
		loader = new Z.Loader({
			'url': Z.route('user', 'records'),
			'listTmpl': bundle.find('script.list-tmpl').html(),
			'list': bundle.find('tbody'),
			'pagination': bundle.find('tfoot td')
		});
		
		loader.load();
	};
	
	Z.BundleList.append(bundle);
})(window);